import pandas as pd
import io
from typing import List, Dict

def generate_excel(test_cases: List[Dict]) -> bytes:
    """生成Excel文件"""
    try:
        if not test_cases:
            raise ValueError("没有测试用例数据")
            
        # 规范化测试用例数据
        normalized_cases = []
        for case in test_cases:
            normalized_case = {
                '用例名称': case.get('用例名称', ''),
                '所属模块': case.get('所属模块', ''),
                '用例等级': case.get('用例等级', ''),
                '前置条件': '\n'.join(case.get('前置条件', [])),
                '测试步骤': '\n'.join(case.get('测试步骤', [])),
                '预期结果': '\n'.join(case.get('预期结果', [])),
                '标签': ', '.join(case.get('标签', []))
            }
            normalized_cases.append(normalized_case)
            
        # 创建DataFrame
        df = pd.DataFrame(normalized_cases)
        
        # 创建一个Excel写入器
        output = io.BytesIO()
        with pd.ExcelWriter(output, engine='openpyxl') as writer:
            df.to_excel(writer, index=False, sheet_name='测试用例')
            
            # 调整列宽
            worksheet = writer.sheets['测试用例']
            for idx, col in enumerate(df.columns):
                # 计算最大列宽
                max_length = max(
                    df[col].astype(str).apply(len).max(),
                    len(str(col))
                )
                # 设置列宽（最大宽度限制为100）
                worksheet.column_dimensions[chr(65 + idx)].width = min(max_length + 2, 100)
                
                # 设置自动换行
                for row in worksheet.iter_rows(min_row=1, max_row=len(df) + 1, min_col=idx + 1, max_col=idx + 1):
                    for cell in row:
                        cell.alignment = cell.alignment.copy(wrapText=True)
        
        # 获取Excel内容
        excel_data = output.getvalue()
        return excel_data
        
    except Exception as e:
        raise Exception(f"生成Excel失败: {str(e)}") 